﻿using System;
using Microsoft.SharePoint;

namespace SPRepository
{
    public class CalculatedFloatFieldType : SimpleFieldType<CalculatedFieldDto<float>>
    {
        public CalculatedFloatFieldType(Guid id) : base(id)
        {
        }

        public override CalculatedFieldDto<float> GetValue(SPListItem item)
        {
            var field = GetField<SPFieldCalculated>(item);
            var fieldValueObject = GetFieldRawValue(item);
            if (fieldValueObject == null)
            {
                return null;
            }
            var fieldValue = (float) fieldValueObject;
            var dto = new CalculatedFieldDto<float>(fieldValue, field.CurrencyLocaleId);
            return dto;
        }

        public override void SetValue(SPListItem item, CalculatedFieldDto<float> value)
        {
            if (value == null)
            {
                item[FieldId] = null;
            }
            else
            {
                item[FieldId] = value.Value;
            }
        }

        private static string GetValueForCalculatedField(SPFieldCalculated field, object val)
        {
            const string separator = SPRepositoryConstants.LookupValueSeperator;

            switch (field.OutputType)
            {
                case SPFieldType.Number:
                case SPFieldType.Currency:
                    return "FLOAT" + separator + val;
                case SPFieldType.DateTime:
                    return "DATETIME" + separator + val;
                case SPFieldType.Boolean:
                    return "BOOLEAN" + separator + val;
                default:
                    return "TEXT" + separator + val;
            }
        }
    }
}